package com.vaadin.tutorial.crm.ui.view.list;

import com.vaadin.tutorial.crm.ui.MainLayout;
import com.vaadin.flow.component.Component;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.Image;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.value.ValueChangeMode;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.StreamResource;
import com.vaadin.tutorial.crm.backend.entity.Student;
import com.vaadin.tutorial.crm.backend.service.StudentService;
import org.springframework.security.access.annotation.Secured;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Iterator;

@Route(value = "stu-list", layout = MainLayout.class)
@PageTitle("stuList")
@Tag("stuList-view")
public class StudentView extends VerticalLayout {
    private StudentService studentService;
    private StudentForm stuForm;
    
    private Grid<Student> grid = new Grid<>(Student.class);
    private TextField filterText = new TextField();

    public StudentView(StudentService studentService) {
        this.studentService = studentService;
        configureGrid();
        //表单
        stuForm = new StudentForm();
        stuForm.addListener(StudentForm.SaveEvent.class, this::saveStudent);
        stuForm.addListener(StudentForm.DeleteEvent.class, this::deleteStudent);
        stuForm.addListener(StudentForm.CloseEvent.class, e -> closeEditor());

        //将表格、表单添加到一个div
        Div div = new Div(grid, stuForm);
        div.addClassName("main");
        div.setSizeFull();

        //将toolbar、div添加到界面
        add(getToolbar(), div);
        updateList("");
        closeEditor();
//        add(grid);
//        updateList();
    }

    private void updateList() {
        grid.setItems(studentService.findAll());
    }

    private void configureGrid() {
        grid.addClassName("student-grid");
//        grid.setSizeFull();
        grid.removeAllColumns();
//        grid.removeColumnByKey("stuId");
//        grid.removeColumnByKey("stuNum");
//        grid.removeColumnByKey("stuName");
//        grid.removeColumnByKey("stuGender");
//        grid.removeColumnByKey("stuBirth");
//        grid.removeColumnByKey("stuPhone");
//        grid.removeColumnByKey("phoneFamily");
//        grid.removeColumnByKey("stuMonitor");
//        grid.removeColumnByKey("stuCollege");

        grid.addColumn("stuNum").setHeader("学号");
        grid.addColumn("stuName").setHeader("姓名");
        grid.addColumn(student -> {
            Student.StuGender stuGender = student.getStuGender();
            if (stuGender.getIndex() == 0){
                return "女";
            }else{
                return "男";
            }

        }).setHeader("性别");

//        grid.addColumn("stuGender").setHeader("性别");
        grid.addColumn("stuBirth").setHeader("出生日期");
        grid.addColumn("stuPhone").setHeader("联系电话");
        grid.addColumn("phoneFamily").setHeader("家庭联系电话");
        grid.addColumn("stuMonitor").setHeader("辅导员");
        grid.addColumn("stuCollege").setHeader("所属学院");
        grid.addComponentColumn(student -> {
            return createComponent(student.getStuPhoto(),"");
        }).setHeader("照片");
        grid.getColumns().forEach(col -> col.setAutoWidth(true));

        //点击表格中的某一列添加到表单中
        grid.asSingleSelect().addValueChangeListener(event ->
                editStudent(event.getValue()));
    }

    //搜索框和添加按钮作为一个toolbar
    private HorizontalLayout getToolbar() {
        filterText.setPlaceholder("请输入学号或姓名...");
        filterText.setClearButtonVisible(true);
        filterText.setValueChangeMode(ValueChangeMode.LAZY);
        filterText.addValueChangeListener(e -> updateList(e.getValue()));

        Button addStudentButton = new Button("新增学生信息");
        addStudentButton.addClickListener(click -> addStudent());

        HorizontalLayout toolbar = new HorizontalLayout(filterText, addStudentButton);
        toolbar.addClassName("toolbar");
        return toolbar;
    }

    //更新表格
    private void updateList(String value) {
        grid.setItems(studentService.findAll(value));
    }

    //清除表单的值
    private void closeEditor() {
        stuForm.setStudent(null);
        stuForm.setVisible(false);
        removeClassName("editing");
    }

    public void editStudent(Student contact) {
        if (contact == null) {
            closeEditor();
        } else {
            stuForm.setStudent(contact);
            stuForm.setVisible(true);
            addClassName("editing");
        }
    }

    //保存
    private void saveStudent(StudentForm.SaveEvent event) {
        studentService.save(event.getStudent());
        updateList("");
        closeEditor();
    }

    //删除
    private void deleteStudent(StudentForm.DeleteEvent event) {
        studentService.delete(event.getStudent());
        updateList("");
        closeEditor();
    }

    void addStudent() {
        grid.asSingleSelect().clear();
        editStudent(new Student());
    }

    //图片组件
    private Component createComponent(byte[] bytes, String fileName) {
        Image image = new Image();
        try {
            image.getElement().setAttribute("src", new StreamResource(
                    fileName, () -> new ByteArrayInputStream(bytes)));
            try (ImageInputStream in = ImageIO.createImageInputStream(
                    new ByteArrayInputStream(bytes))) {
                final Iterator<ImageReader> readers = ImageIO
                        .getImageReaders(in);
                if (readers.hasNext()) {
                    ImageReader reader = readers.next();
                    try {
                        reader.setInput(in);
//                            image.setWidth(reader.getWidth(0) + "px");
//                            image.setHeight(reader.getHeight(0) + "px");
                        image.setWidth(50+ "px");
                        image.setHeight(50 + "px");
                    } finally {
                        reader.dispose();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }
}
